package com.my.db.init;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

/**
 * 项目初始化时运行mysql 初始化 脚本
 */
@Component
@Order(value = 2)
@Slf4j
public class SqlApplicationRunner implements ApplicationRunner {

    private static String url;

    private static String userName;

    private static String userPassword;

    @Value("${spring.datasource.url}")
    public void setUrl(String url) {
        this.url = url;
    }

    @Value("${spring.datasource.username}")
    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Value("${spring.datasource.password}")
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("=============开始执行sql脚本=============");
        try {
            //从class目录下直接读取
//            Resource classPathResource = new ClassPathResource("init.sql");
//            ScriptUtils.executeSqlScript(dataSource.getConnection(), classPathResource);

//            Connection conn = getOracleConnection();
//            ScriptRunner runner = new ScriptRunner(conn);
//            Resources.setCharset(Charset.forName("UTF-8")); //设置字符集,不然中文乱码插入错误
//            runner.setLogWriter(null);//设置是否输出日志
//            List<File> varList = getFiles("/home/java/sqls");
//            for (File file : varList) {
//                // 绝对路径读取
//                Reader read = new FileReader(file);
//                //从class目录下直接读取
////                Reader read = Resources.getResourceAsReader("test.sql");
//                runner.runScript(read);
//            }
//            runner.closeConnection();
//            conn.close();
            log.info("=============初始化sql脚本数据到数据库完成=============");
        } catch (Exception e) {
            log.error("初始化时sql脚本数据到数据库", e);
            log.error("=============初始化sql脚本数据到数据库失败！！！=============");
        }
    }

    /**
     * 获取数据库连接
     * @return
     * @throws Exception
     */
    public static Connection getOracleConnection() throws Exception {
        Class.forName("oracle.jdbc.OracleDriver");
        return DriverManager.getConnection(url, userName, userPassword);
    }

    /**
     * @Description：获取某个目录下所有直接下级文件，不包括目录下的子目录的下的文件，所以不用递归获取
     * @param path
     * @return
     */
    public static List<File> getFiles(String path) {
        List<File> files = new ArrayList<>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i]);
                //文件名，不包含路径
                //String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
        return files;
    }
}